import configparser
import json
import os.path
import tarfile
import zipfile

import py7zr

base_dir = os.path.dirname(os.path.dirname(__file__))


class Config:
    __APP_DATA__ = os.environ['APPDATA']

    CONFIG_PATH = os.path.join(__APP_DATA__, 'BlueTool.json')

    @classmethod
    def read_config(cls):
        if not os.path.exists(cls.CONFIG_PATH):
            return {}
        with open(cls.CONFIG_PATH, 'r') as f:
            data = json.load(f)
        return data

    @classmethod
    def save_config(cls, config_data: dict):
        if not config_data:
            return
        with open(cls.CONFIG_PATH, 'w') as f:
            json.dump(config_data, f)


def empty_folder(folder):
    """
    清空目录及下面所有的文件
    :param folder:
    :return:
    """
    son_folders = []
    for file in os.listdir(folder):
        file_path = os.path.join(folder, file)
        # 如果是文件夹，则递归删除
        if os.path.isdir(file_path):
            son_folders.append(file_path)
            empty_folder(file_path)
        else:
            os.remove(file_path)
    for it in reversed(son_folders):
        os.rmdir(it)


def decompress_file(compress_file, extract_to=''):
    """
    解压文件
    :param compress_file:
    :param extract_to:
    :return:
    """
    if not compress_file:
        return
    # 如果没给解压后的目录默认解压到当前目录
    if not extract_to:
        extract_to = os.path.dirname(compress_file)
    if compress_file.endswith('.tar.gz'):
        with tarfile.open(compress_file) as tf:
            tf.extractall(extract_to)
    elif compress_file.endswith('.zip'):
        with zipfile.ZipFile(compress_file, 'r') as zip_ref:
            zip_ref.extractall(extract_to)
    elif compress_file.endswith('.7z'):
        with py7zr.SevenZipFile(compress_file, mode='r') as z:
            z.extractall(path=extract_to)
